﻿/*
	This file is part of Limpet.

    Limpet is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Limpet is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with Limpet.  If not, see http://www.gnu.org/licenses/.
	
	Copyright 2010 Dan Popick
*/

using System;
using System.Net;
using System.Web;

namespace Open.Web.Diagnostics.Limpet
{
    /// <summary>
    /// An HTTP Handler which renders the details for self-rendering limpet modules
    /// </summary>
    public class LimpetHandler : IHttpHandler, System.Web.SessionState.IRequiresSessionState
    {
        /// <summary>
        /// Processes the HTTP request
        /// </summary>
        /// <param name="context">The current HTTP Context</param>
        public void ProcessRequest(HttpContext context)
        {
            if (LimpetManager.Config.AllowedAddresses.Count > 0)
            {
                IPAddress addr;
                if (!IPAddress.TryParse(context.Request.UserHostAddress, out addr))
                {
                    context.Response.StatusCode = 403;
                    return;
                }

                if (!IPUtil.FindSubnetMatch(addr, LimpetManager.Config.AllowedAddresses))
                {
                    context.Response.StatusCode = 403;
                    return;
                }
            }

            context.Response.Filter = new PageFilterEncryptionStream(new Base64EncodingStream(context.Response.Filter));

            context.Response.ContentType = "text/html";

            string moduleName = context.Request.QueryString["module"];

            if (context.Request.Cookies[LimpetManager.Config.CookieName] == null)
                return;

            ISelfRenderingLimpetModule module = LimpetManager.GetModule(moduleName) as ISelfRenderingLimpetModule;
            if (module == null)
                return;

            module.RenderDetails(context.Response.OutputStream);
        }

        // this is always reusable
        public bool IsReusable { get { return true; } }
    }
}